// --------------------------------------------------------------------------------------------------------------------
// <copyright file="InstrumentExpoCell.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework.Forge
{
    #region Usings

    using System;
    using System.ComponentModel;

    using Org.OpenTrader.Framework.Forge.Enums;
    using Org.OpenTrader.Framework.Forge.Events;
    using Org.OpenTrader.Framework.Forge.Interfaces;

    #endregion

    /// <summary>
    /// The instrument expo cell.
    /// </summary>
    public abstract class InstrumentExpoCell : IInstrumentExpoCell
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="InstrumentExpoCell"/> class.
        /// </summary>
        /// <param name="instrument">
        /// The instrument.
        /// </param>
        public InstrumentExpoCell(IInstrument instrument)
        {
            // Instrument
            this.Instrument = instrument;
        }

        #endregion

        #region Events

        /// <summary>
        /// Order Event Handler
        /// </summary>
        public event EventHandler<OrderEventArgs> OrderEventCB;

        #endregion

        /////// <summary>
        /////// The order event handler.
        /////// </summary>
        ////public event EventHandler<OrderEventArgs> OrderEventCB
        ////{
        ////    add
        ////    {
        ////        if (value == null)
        ////        {
        ////            throw new NullReferenceException("OrderEventCB: += null");
        ////        }

        ////        // First time
        ////        if (this.OrderEventCB == null)
        ////        {
        ////            this.OrderEventCB = value;
        ////            return;
        ////        }

        ////        // Following times
        ////        this.OrderEventCB += value;
        ////    }

        ////    remove
        ////    {
        ////        if (value == null)
        ////        {
        ////            throw new NullReferenceException("OrderEventCB: -= null");
        ////        }

        ////        // Remove
        ////        this.OrderEventCB -= value;
        ////    }
        ////}
        #region Properties

        /// <summary>
        /// Gets the average price of the inventory
        /// </summary>
        public virtual double AveragePrice
        {
            get
            {
                if (this.IsLong)
                {
                    return this.BuyAverageExecutedPrice;
                }

                if (this.IsShort)
                {
                    return this.SellAverageExecutedPrice;
                }

                return 0.0;
            }
        }

        /// <summary>
        /// Average price of executed buy orders
        /// </summary>
        public virtual double BuyAverageExecutedPrice { get; protected set; }

        /// <summary>
        /// Cumulative quantity of executed buy orders : >0
        /// </summary>
        public virtual int BuyExecutedQty { get; protected set; }

        /// <summary>
        /// Gets the total executed qty : BuyExecutedQty + SellExecutedQty
        /// </summary>
        public virtual int ExecutedQty
        {
            get
            {
                return this.BuyExecutedQty + this.SellExecutedQty;
            }
        }

        /// <summary>
        /// Gets Expo Type
        /// </summary>
        public abstract EExpoCellType ExpoType { get; protected set; }

        /// <summary>
        /// Factor Price
        /// </summary>
        public double FactorPrice
        {
            get
            {
                if (this.Instrument == null)
                {
                    return 0.0;
                }

                if (this.Instrument.InstrumentStaticData == null)
                {
                    return 0.0;
                }

                if (!this.Instrument.InstrumentStaticData.FactorPrice.HasValue)
                {
                    return 0.0;
                }

                return this.Instrument.InstrumentStaticData.FactorPrice.Value;
            }
        }

        /// <summary>
        /// Gets Fees
        /// </summary>
        public double Fees
        {
            get
            {
                if (this.FeesTracker == null)
                {
                    return 0.0;
                }

                return this.FeesTracker.Fees;
            }
        }

        /// <summary>
        /// Gets FeesTracker.
        /// </summary>
        [Category("Instrument Fees")]
        public IFeesTracker FeesTracker { get; protected set; }

        /// <summary>
        /// Gets or sets Instrument.
        /// </summary>
        public IInstrument Instrument { get; private set; }

        /// <summary>
        /// Gets the inventory : BuyExecutedQty - SellExecutedQty
        /// </summary>
        public virtual int Inventory
        {
            get
            {
                return this.BuyExecutedQty - this.SellExecutedQty;
            }
        }

        /// <summary>
        /// The inventory event delegate.
        /// </summary>
        public abstract InventoryEventDelegate InventoryEventDelegate { get; }

        /// <summary>
        /// Check if the vales are changed
        /// </summary>
        public bool IsChanged { get; protected set; }

        /// <summary>
        /// TRUE if no position are open on this symbol
        /// </summary>
        public virtual bool IsClosed
        {
            get
            {
                return this.BuyExecutedQty == this.SellExecutedQty;
            }
        }

        /// <summary>
        /// TRUE if BuyExecutedQty > SellExecutedQty
        /// </summary>
        public virtual bool IsLong
        {
            get
            {
                return this.BuyExecutedQty > this.SellExecutedQty;
            }
        }

        /// <summary>
        /// TRUE if position are open on this symbol
        /// </summary>
        public virtual bool IsOpen
        {
            get
            {
                return this.BuyExecutedQty != this.SellExecutedQty;
            }
        }

        /// <summary>
        /// TRUE if SellExecutedQty > BuyExecutedQty  
        /// </summary>
        public virtual bool IsShort
        {
            get
            {
                return this.BuyExecutedQty < this.SellExecutedQty;
            }
        }

        /// <summary>
        /// Check if updated
        /// </summary>
        public bool IsUpdated { get; protected set; }

        /// <summary>
        /// Check if is updating values
        /// </summary>
        public bool IsUpdating { get; protected set; }

        /// <summary>
        /// LastUpdate Time
        /// </summary>
        public DateTime LastUpdate { get; protected set; }

        /// <summary>
        /// Gets NetPL.
        /// </summary>
        public virtual double NetPL
        {
            get
            {
                if (this.FeesTracker == null)
                {
                    return this.PL;
                }

                return this.PL - this.FeesTracker.Fees;
            }
        }

        /// <summary>
        /// Return the market expo : Long - Short
        /// </summary>
        public virtual double NominalExpo
        {
            get
            {
                return this.NominalLong - this.NominalShort;
            }
        }

        /// <summary>
        /// Returns the nominal long = BuyExecutedQty * BuyAverageExecutedPrice
        /// </summary>
        public virtual double NominalLong
        {
            get
            {
                return this.BuyExecutedQty * this.BuyAverageExecutedPrice;
            }
        }

        /// <summary>
        /// Returns the nominal short = SellExecutedQty * SellAverageExecutedPrice
        /// </summary>
        public virtual double NominalShort
        {
            get
            {
                return this.SellExecutedQty * this.SellAverageExecutedPrice;
            }
        }

        /// <summary>
        /// The order event delegate.
        /// </summary>
        public abstract OrderEventDelegate OrderEventDelegate { get; }

        /// <summary>
        /// Gets PL.
        /// </summary>
        public virtual double PL
        {
            get
            {
                if (this.RefPrice < Constants.Zero)
                {
                    return 0.0;
                }

                return (this.SellAverageExecutedPrice * (double)this.SellExecutedQty) - (this.BuyAverageExecutedPrice * (double)this.BuyExecutedQty) +
                       (double)((this.BuyExecutedQty - this.SellExecutedQty) * this.RefPrice);
            }
        }

        /// <summary>
        /// Gets Realized.
        /// </summary>
        public virtual double Realized
        {
            get
            {
                return (double)Math.Min(this.BuyExecutedQty, this.SellExecutedQty) * (this.SellAverageExecutedPrice - this.BuyAverageExecutedPrice);
            }
        }

        /// <summary>
        /// The ref price.
        /// </summary>
        public abstract double RefPrice { get; }

        /// <summary>
        /// Average price of executed sell orders
        /// </summary>
        public virtual double SellAverageExecutedPrice { get; protected set; }

        /// <summary>
        /// Cumulative quantity of executed sell orders : >0
        /// </summary>
        public virtual int SellExecutedQty { get; protected set; }

        /// <summary>
        /// Gets UnRealized.
        /// </summary>
        public virtual double UnRealized
        {
            get
            {
                if (this.RefPrice < Constants.Zero)
                {
                    return 0.0;
                }

                if (this.BuyExecutedQty > this.SellExecutedQty)
                {
                    return (this.BuyExecutedQty - this.SellExecutedQty) * (this.RefPrice - this.BuyAverageExecutedPrice);
                }

                if (this.BuyExecutedQty < this.SellExecutedQty)
                {
                    return (this.BuyExecutedQty - this.SellExecutedQty) * (this.RefPrice - this.SellAverageExecutedPrice);
                }

                return 0.0;
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Set members to default value (null)
        /// </summary>
        public void Init()
        {
            this.BuyExecutedQty = 0;
            this.BuyAverageExecutedPrice = 0.0;
            this.SellExecutedQty = 0;
            this.SellAverageExecutedPrice = 0.0;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Add Qty@Price
        /// </summary>
        /// <param name="way">
        /// The way.
        /// </param>
        /// <param name="qty">
        /// signed qty (-sell, +buy)
        /// </param>
        /// <param name="price">
        /// </param>
        /// <returns>
        /// The add.
        /// </returns>
        protected bool Add(EOrderWay way, int qty, double price)
        {
            if (qty > 0 && price > 0.0)
            {
                if (way == EOrderWay.Buy)
                {
                    // Buy
                    this.BuyAverageExecutedPrice = ((this.BuyAverageExecutedPrice * (double)this.BuyExecutedQty) + (price * (double)qty)) /
                                                   (double)(this.BuyExecutedQty + qty);
                    this.BuyExecutedQty += qty;
                    return true;
                }

                if (way == EOrderWay.Sell)
                {
                    // Sell
                    this.SellAverageExecutedPrice = ((this.SellAverageExecutedPrice * (double)this.SellExecutedQty) + (price * (double)qty)) /
                                                    (double)(this.SellExecutedQty + qty);
                    this.SellExecutedQty += qty;
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// The raise order event.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="args">
        /// The args.
        /// </param>
        protected void ForwardOrderEvent(object sender, OrderEventArgs args)
        {
            if (this.OrderEventCB == null)
            {
                return;
            }

            try
            {
                this.OrderEventCB(this, args);
            }
            catch
            {
            }
        }

        #endregion
    }
}